// src/components/popups/scholarOverview/RecentScholars/RecentScholarsModal.tsx

import type { FC } from 'react';
import { useEffect, useState, useCallback, useMemo } from 'react';
import { fetchRecentScholars } from '@/services/scholarsDashboardService/fetchRencentScholars';
import { fetchRecentScholarSearch } from '@/services/scholarsDashboardService/fetchRecentScholarSearch';
import Pagination from '@/components/scholarDashboard/mainContent/Pagination';
import RecentScholarsSearchText from '@/components/popups/scholarOverview/RecentScholars/RecentScholarsSearchText'

const formatDateForDisplay = (dateString: string | null): string => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return '';
    return date.toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric'
    });
  } catch {
    return '';
  }
};

interface RecentScholar {
  student_number: string | null;
  program_id: string | null;
  full_name: string | null;
  email: string | null;
  scholar_type: string | null;
  most_recent_sponsor: string | null;
  most_recent_ite_start: string | null;
  most_recent_ite_end: string | null;
}

interface RecentScholarsModalProps {
  onClose: () => void;
}

const RecentScholarsModal: FC<RecentScholarsModalProps> = ({ onClose }) => {
  const [results, setResults] = useState<RecentScholar[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [searchText, setSearchText] = useState('');
  const [lastSearched, setLastSearched] = useState('');
  const itemsPerPage = 10;

  const fetchAllData = useCallback(async (keywords: string) => {
    setLoading(true);
    setResults([]);
    setLoadingProgress('');

    try {
      const allResults: RecentScholar[] = [];
      let currentPage = 1;
      let hasMoreData = true;
      const pageSize = keywords.trim() ? 100 : 500;

      while (hasMoreData) {
        setLoadingProgress(`Fetching...`);

        const queryParams = {
          skip: (currentPage - 1) * pageSize,
          limit: pageSize,
          ...(keywords.trim() && { keywords: keywords.trim() })
        };

        const fetchFn = keywords.trim()
          ? fetchRecentScholarSearch(queryParams)
          : fetchRecentScholars(queryParams);

        const response = await fetchFn;

        if (!response || typeof response !== 'object') {
          throw new Error('Invalid response format');
        }

        const scholars = response.scholars || [];

        allResults.push(...scholars);

        const total = response.total || 0;
        const totalPages = Math.ceil(total / pageSize);

        if (currentPage >= totalPages || scholars.length === 0) {
          hasMoreData = false;
        } else {
          currentPage++;
        }
      }

      setTimeout(() => {
        setResults(allResults);
        setLoading(false);
        setLoadingProgress('');
      }, 300);
    } catch (error) {
      console.error('Error fetching scholars:', error);
      setResults([]);
      setLoading(false);
      setLoadingProgress('');
    }
  }, []);

  useEffect(() => {
    fetchAllData('');
  }, [fetchAllData]);

  const handleSearch = (val: string) => {
    setCurrentPage(1);
    setLastSearched(val);
    fetchAllData(val);
  };

  const paginatedResults = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    return results.slice(startIndex, endIndex);
  }, [results, currentPage, itemsPerPage]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 dark:bg-black/80 backdrop-blur-sm p-2 sm:p-4 font-poppins text-xs sm:text-sm md:text-base"
      onClick={onClose}
    >
      <div
        className="w-full max-w-5xl bg-white dark:bg-slate-900 rounded-2xl shadow-2xl dark:shadow-blue-900 overflow-hidden animate-fade-in-up max-h-[90vh] overflow-y-auto relative border border-gray-200 dark:border-slate-800"
        onClick={e => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 sm:px-6 py-4 sm:py-5 bg-white dark:bg-slate-900 text-gray-800 dark:text-cyan-200 flex justify-between items-center border-b border-gray-200 dark:border-slate-800 rounded-t-2xl shadow-sm text-xs sm:text-sm md:text-base">
          <h2 className="text-base sm:text-lg md:text-2xl font-extrabold tracking-tight break-words text-blue-700 dark:text-cyan-300">
            Recent Scholars Overview
          </h2>
          <button
            onClick={onClose}
            className="w-9 h-9 flex items-center justify-center rounded-full text-xl font-bold text-gray-500 dark:text-gray-300 hover:text-red-600 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-900 transition focus:outline-none focus:ring-2 focus:ring-red-300 dark:focus:ring-red-800"
          >
            ×
          </button>
        </div>

        {/* Search Bar */}
        <div className="px-4 sm:px-6 pt-4 pb-2 bg-white dark:bg-slate-900">
          <RecentScholarsSearchText
            value={searchText}
            onChange={setSearchText}
            onSearch={handleSearch}
            loading={loading}
            placeholder="Search by name, email, or student number..."
            showBackAll={!!lastSearched}
          />
        </div>

        {/* Body */}
        <div className="p-3 sm:p-6 space-y-4 text-xs sm:text-sm md:text-base text-gray-800 dark:text-gray-100 bg-white dark:bg-slate-900">
          {loading ? (
            <div className="text-center text-gray-400 dark:text-gray-500 animate-pulse py-8 text-base sm:text-lg">
              {loadingProgress || 'Loading results...'}
            </div>
          ) : (
            <div className="w-full overflow-x-auto mt-2 rounded-2xl shadow bg-white dark:bg-slate-900 border border-gray-200 dark:border-slate-800">
              <table className="min-w-[900px] w-full text-xs sm:text-sm md:text-base rounded-2xl overflow-hidden">
                <thead className="bg-blue-50 dark:bg-slate-800 border-b-2 border-gray-200 dark:border-slate-700 shadow-sm">
                  <tr>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Student Number</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Program ID</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Full Name</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Email</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Scholar Type</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Most Recent Sponsor</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Most Recent ITE Start</th>
                    <th className="px-4 py-2 text-left font-bold text-gray-700 dark:text-cyan-300 tracking-wide whitespace-nowrap">Most Recent ITE End</th>
                  </tr>
                </thead>
                <tbody>
                  {results.length === 0 ? (
                    <tr>
                      <td colSpan={8} className="text-center py-6 text-gray-400 dark:text-gray-500 italic bg-gray-50 dark:bg-slate-900 rounded-b-2xl">
                        {lastSearched ? 'No scholars found matching your search criteria.' : 'No recent scholar records found.'}
                      </td>
                    </tr>
                  ) : (
                    paginatedResults.map((row, idx) => (
                      <tr key={idx} className="hover:bg-blue-50 dark:hover:bg-slate-700 transition">
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.student_number || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.program_id || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.full_name || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.email || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.scholar_type || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{row.most_recent_sponsor || ''}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{formatDateForDisplay(row.most_recent_ite_start)}</td>
                        <td className="px-4 py-2 text-gray-800 dark:text-gray-100 border-b border-gray-100 dark:border-slate-700 whitespace-nowrap">{formatDateForDisplay(row.most_recent_ite_end)}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          )}

          {results.length > itemsPerPage && (
            <Pagination
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalCount={results.length}
              pageSize={itemsPerPage}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default RecentScholarsModal;